/******************************************************************************/
/* Files to Include                                                           */
/******************************************************************************/

#include "user.h"
#include <adc.h>
#include <delays.h>
#include "XLCD/xlcd.h"


/******************************************************************************/
/* User Functions                                                             */
/******************************************************************************/

/* <Initialize variables in user.h and insert code for user algorithms.> */

void InitApp(void)
{

/*--initialize ADC---*/
    unsigned char config1=0x00,config2=0x00,portconfig=0x00;
/*-- clear adc interrupt and turn off adc if in case was on prerviously---*/
    CloseADC();

    /**** ADC configured for:
     
     * FOSC/4 as source conversion clock.
     * At 4MHz clock, selecting ADCS = FOSC/4 = 1MHz, then TAD = 1.0 useg.
     * Total conversion time = 11 TAD = 11useg.
     
     * Sample aquisition time of 20 TAD. When the GO/DONE bit is set,
     * the A/D module continues to sample the input for 2 TAD,
     * then automatically begins a conversion.

     *  Time from A/D begins sampling to conversion completed is:
     *                 20 TAD + 11 TAD = 31 TAD = 31 useg

     * Result is right justified.
    */
     config1 = ADC_FOSC_4 & ADC_20_TAD & ADC_RIGHT_JUST;

    /***** ADC configured for(cont.2):
    * Channel 0 for sampling
    * ADC interrupt off
    * ADC reference voltage from VDD & VSS
    */
    config2 = ADC_CH0 & ADC_INT_ON & ADC_REF_VDD_VSS;

  /***** ADC configured for(cont.3):
  * AN0 pin is enabled as an analog input as the demo board potentiometer is
  * connected to RA0/AN0.Remaining channels are digital.
  */
    portconfig = ADC_1ANA;

    OpenADC(config1,config2,portconfig);

/*--Initialize LCD ---*/

    OpenXLCD( FOUR_BIT & LINES_5X7 );

    /*CURSOR_OFF*/
    SendCommandXLCD (CURSOR_OFF & BLINK_OFF);
    
    /*Set entry mode incremental*/
    SendCommandXLCD(SHIFT_DISP_LEFT);

}

void DelayFor18TCY(void)
{   /* Delay for 18 cycles*/
    Delay10TCYx(2);
}

void DelayPORXLCD(void)
{   /* Delay for 15 ms */
    Delay1KTCYx(15);
}

void DelayXLCD(void)
{   /* Delay for 5 ms */
    Delay1KTCYx(5);
}

void SendCommandXLCD(unsigned char cmd)
{
    while( BusyXLCD() );
    WriteCmdXLCD(cmd);
}